<template>
  <view class="free-deposit-wrapper">
    <ve-card>
      <ve-cell label="自有订单号">{{ depositDetail.orderCode }}</ve-cell>
      <ve-cell label="承租人">{{ depositDetail.memberNamePhone }}</ve-cell>
      <ve-cell label="免押用户手机号">{{ depositDetail.freeMemberPhone || '-' }}</ve-cell>
      <ve-cell-price label="租车押金" :value="depositDetail.carDepositAmount" />
      <ve-cell-price label="违章押金" :value="depositDetail.illegalDepositAmount" />
    </ve-card>
    <ve-card>
      <ve-cell-price label="剩余可操作金额" :value="depositDetail.availableDepositAmount" />
      <ve-cell class="custom-cell">
        <template #label>
          押金预计解冻日期
          <ve-tooltip placement="top-start">
            <template #content>
              <view class="tips-item">1、未操作租车转违章前，押金最长冻结天数为{{ `${depositDetail.freezeDay}天` }}；</view>
              <view class="tips-item"
                >2、操作租车转违章后，未超过配置{{ `${depositDetail.freezeDay}天` }}，押金最长冻结天数为{{
                  `${depositDetail.violationFreezeDay}天`
                }}；</view
              >
            </template>
            <ve-icon name="help" width="36" height="36" />
          </ve-tooltip>
        </template>
        {{ depositDetail.planThawTime || '-' }}
      </ve-cell>
      <ve-cell class="custom-cell payment-num">
        <template #label
          >已扣款次数
          <ve-tooltip placement="top-start">
            <template #content>
              <view>1、支付宝方每笔押金最多可扣款5次；</view>
              <view>2、已扣款次数仅统计扣款成功的次数；</view>
            </template>
            <ve-icon name="help" width="36" height="36" />
          </ve-tooltip>
        </template>
        <view class="payment-num-content">
          <view class="payment-num-text">
            {{ depositDetail.cutPaymentNum || depositDetail.cutPaymentNum === 0 ? Number(depositDetail.cutPaymentNum) : '-' }} 次
          </view>
          <!-- 剩余可扣款次数 x 次 -->
          <view class="surplus-num">
            剩余可扣款次数 {{ depositDetail.surplusNum || depositDetail.surplusNum === 0 ? Number(depositDetail.surplusNum) : '-' }} 次
          </view>
        </view>
      </ve-cell>

    </ve-card>
    <!-- 操作区域 -->
    <view class="operates" v-if="!hideOperate">
      <view class="operate-item" v-for="item in operateList" :key="item" @click="onOperateClick(item)"> {{ item.name }} </view>
    </view>
    <!-- 押金变更记录表 -->
    <freeDepositRecord
      v-if="depositDetail.depositRecordList && depositDetail.depositRecordList.length > 0"
      :list="depositDetail.depositRecordList"
    />
    <ve-empty v-else />
  </view>
</template>
<script setup>
  import { ref, onMounted, onUnmounted, computed } from 'vue'
  import { getSOrderDepositDetail, checkDepositOperate } from '@/api/order/sOrder'
  import freeDepositRecord from './free-deposit-record/record.vue'
  import { usePermission } from '@/hooks/usePermission'
  import dayjs from 'dayjs'

  const props = defineProps({
    orderId: {
      type: [String, Number],
    },
    // 是否隐藏操作
    hideOperate: Boolean,
  })

  const operateList = computed(() => {
    const info = depositDetail.value
    const operates = [
      {
        name: '租车转违章',
        type: 'transfer',
        // 1 芝麻免押
        // 2 且该条押金未操作过租车转违章
        // 3 租车押金状态为应收已收或应退未退状态
        show: info.payType == 4 && info.carRentalChangeViolation == 0 && [30, 50].includes(info.carDepositStatus),
        permission: usePermission('svmsapp:order:short-order.deposit.rentaltoviolation'),
      },
      {
        name: '全部解冻',
        type: 'unfreeze',
        // 1 芝麻免押
        // 2 剩余可用押金金额>0
        show: info.payType == 4 && info.availableDepositAmount > 0,
        permission: usePermission('svmsapp:order:short-order.deposit.allthaw'),
      },
      {
        name: '押金扣款',
        type: 'depositDeduction',
        // 1 芝麻免押
        // 2 剩余可用押金金额>0
        show: info.payType == 4 && info.availableDepositAmount > 0,
        permission: usePermission('svmsapp:order:short-order.deposit.deduction'),
      },
    ]

    return operates.filter((item) => item.show && item.permission)
  })

  // 操作
  const onOperateClick = (item) => {
    const param = {
      id: props.orderId,
      type: item.type == 'transfer' ? 1 : undefined,
    }
    // 押金可操作验证
    checkDepositOperate(param).then((res) => {
      const result = res.result
      if (result) {
        const { errorCode, currentlyAvailableDepositAmount, receivedDepositAmount, violationFreezeDay } = result
        let carChangeViPlanThawTime = result.carChangeViPlanThawTime
        if (carChangeViPlanThawTime) {
          carChangeViPlanThawTime = dayjs(carChangeViPlanThawTime).format('YYYY-MM-DD')
        }
        if (errorCode == 200) {
          switch (item.type) {
            case 'transfer':
              // 转违章押金
              uni.navigateTo({
                url: `/pages/order/short-order/components/transfer-violation?carDepositId=${depositDetail.value.carDepositId}&avaliableAmount=${currentlyAvailableDepositAmount}&receiveAmount=${receivedDepositAmount}&freezeDay=${violationFreezeDay}&planThawTime=${carChangeViPlanThawTime}`,
              })
              break
            case 'unfreeze':
              // 全部解冻
              uni.navigateTo({
                url: `/pages/order/short-order/components/unfreeze-all?id=${depositDetail.value.id}&availableDepositAmount=${depositDetail.value.availableDepositAmount}`,
              })
              break
            case 'depositDeduction':
              // 押金扣款
              uni.navigateTo({
                url: `/pages/order/short-order/free-deposit-deduction?orderId=${props.orderId}`,
              })
              break
          }
        } else if (errorCode == 888) {
          let tip
          if (item.type == 'transfer') tip = '押金已不支持租车转违章'
          if (item.type == 'unfreeze') tip = '押金已不支持全部解冻'
          if (item.type == 'depositDeduction') tip = '押金已不支持扣款'
          // 转违章押金
          uni.showToast({
            icon: 'none',
            title: tip,
          })
        } else if (errorCode == 999) {
          let tip
          if (item.type == 'transfer') tip = '存在请求中的数据，暂不支持租车转违章'
          if (item.type == 'unfreeze') tip = '存在请求中的数据，暂不支持全部解冻'
          if (item.type == 'depositDeduction') tip = '存在请求中的数据，暂不支持押金扣款'
          uni.showToast({
            icon: 'none',
            title: tip,
          })
        }
      }
    })
  }

  // 押金信息
  const depositDetail = ref({})
  const getDepositDetail = () => {
    const id = props.orderId
    getSOrderDepositDetail({ orderId: id, orderType: 1 }).then((res) => {
      const result = res.result
      if (result) {
        // 承租人信息
        const temp = []
        if (result.memberName) temp.push(result.memberName)
        if (result.memberPhone) temp.push(result.memberPhone)
        result.memberNamePhone = temp.join(' | ')
        // 格式化押金预计解冻日期
        let planThawTime = result.planThawTime
        if (planThawTime) {
          planThawTime = dayjs(planThawTime).format('YYYY-MM-DD')
        }
        result.planThawTime = planThawTime
        // 格式化创建时间
        const depositRecordList = result.depositRecordList
        if (depositRecordList && depositRecordList.length > 0) {
          depositRecordList.forEach((record) => {
            if (record.createTime) record.createTime = dayjs(record.createTime).format('YYYY-MM-DD HH:mm')
          })
        }
      }
      depositDetail.value = result
    })
  }

  onMounted(() => {
    getDepositDetail()

    uni.$on('refreshData', getDepositDetail)
  })
  onUnmounted(() => {
    uni.$off('refreshData', getDepositDetail)
  })
</script>
<style lang="less" scoped>
  .free-deposit-wrapper {
    padding: 24rpx;
    .custom-cell {
      .ve-tooltip {
        display: inline;
        /deep/ .ve_tooltip_content {
          display: inline;
        }
      }
      &.payment-num {
        position: relative;
        margin-bottom: 0;
        .ve-tooltip {
          position: absolute;
          left: 154rpx;
          top: -5rpx;
        }
      }
      .tips-item {
        width: 570rpx;
        word-wrap: break-word;
        white-space: normal;
      }
    }
    .surplus-num {
      text-align: center;
      height: 44rpx;
      font-size: 30rpx;
      color: #3072f6;
      line-height: 44rpx;
      margin: 16rpx 0 32rpx;
    }
    .operates {
      display: flex;
      margin: 24rpx 0;

      .operate-item {
        width: calc(33.3% - 22.66rpx);
        height: 64rpx;
        line-height: 60rpx;
        border-radius: 4rpx 4rpx 4rpx 4rpx;
        border: 2rpx solid #3072f6;
        text-align: center;
        font-size: 28rpx;
        color: #3072f6;
      }
      .operate-item + .operate-item {
        margin-left: 34rpx;
      }
    }
  }
</style>
